package org.jeecg.modules.demo.widthmanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.widthmanagement.entity.WidthManagement;
import org.jeecg.modules.demo.widthmanagement.entity.WidthManagmentInfo;
import org.jeecg.modules.demo.widthmanagement.service.IWidthManagementService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecg.modules.weixin.util;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 股东提现管理
 * @Author: jeecg-boot
 * @Date: 2022-01-14
 * @Version: V1.0
 */
@Api(tags = "股东提现管理")
@RestController
@RequestMapping("/widthmanagement/widthManagement")
@Slf4j
public class WidthManagementController extends JeecgController<WidthManagement, IWidthManagementService> {
    @Autowired
    private IWidthManagementService widthManagementService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IMsgTemplateService msgTemplateListService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param widthManagement
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "股东提现管理-分页列表查询")
    @ApiOperation(value = "股东提现管理-分页列表查询", notes = "股东提现管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(WidthManagement widthManagement,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        QueryWrapper<WidthManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        Map<String, String[]> parameterMap = req.getParameterMap();
        QueryGenerator.initQueryWrapper(queryWrapper, widthManagement, parameterMap);
        if(parameterMap.containsKey("startTime")){
            queryWrapper.between("create_time",parameterMap.get("startTime")[0]+" 00:00:00",parameterMap.get("endTime")[0]+" 23:59:59");
        }
        Page<WidthManagement> page = new Page<WidthManagement>(pageNo, pageSize);
        IPage<WidthManagement> pageList = widthManagementService.page(page, queryWrapper);

        // 为了保持返回值不变，沿用框架的分页方式。分页查询后用每项的商品id查商品详情
        List<WidthManagement> records = pageList.getRecords();
        List<Map<String, Object>> records1 = records.stream().map(wm -> {
            Map<String, Object> m = ToolsUtils.objectToMap(wm);
            StockManage stock = stockManageService.getById(wm.getStockId());
            if (stock != null) {
                m.put("stockName", stock.getStockName());
                m.put("tel", stock.getTel());
            }
            m.put("statusName", "00".equals(wm.getStatus()) ? "未审核" : "01".equals(wm.getStatus()) ? "通过" : "驳回");
            Date createTime = (Date) m.get("createTime");
            Date updateTime = (Date) m.get("updateTime");
            if (createTime != null) {
                m.put("createTime", sdf.format(createTime));
            }
            if (updateTime != null) {
                m.put("updateTime", sdf.format(updateTime));
            }
            return m;
        }).collect(Collectors.toList());
        IPage<Map<String, Object>> pageList1 = new PageDTO<>();
        BeanUtils.copyProperties(pageList, pageList1);
        pageList1.setRecords(records1);
        return Result.OK(pageList1);
    }

    /**
     * 查询提现记录
     */
    @RequestMapping(value = "/getWidthManagmentList", method = RequestMethod.GET)
    public Result<List<WidthManagmentInfo>> getWidthManagmentList(
            @RequestParam(name = "pageNo", required = true) Integer pageNo,
            @RequestParam(name = "storeId", required = true) String storeId,
            @RequestParam(name = "stockId", required = true) String stockId) {
        Result<List<WidthManagmentInfo>> result = new Result<>();
        List<WidthManagmentInfo> list = widthManagementService.getWidthManagmentList(pageNo, 10, storeId, stockId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 添加
     *
     * @param widthManagement
     * @return
     */
    @AutoLog(value = "股东提现管理-添加")
    @ApiOperation(value = "股东提现管理-添加", notes = "股东提现管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WidthManagement widthManagement, HttpServletRequest req) {
        //HttpServletRequest req
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        widthManagement.setStoreId(storeId);
        widthManagementService.save(widthManagement);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param widthManagement
     * @return
     */
    @AutoLog(value = "股东提现管理-编辑")
    @ApiOperation(value = "股东提现管理-编辑", notes = "股东提现管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody WidthManagement widthManagement) {

        widthManagementService.updateById(widthManagement);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "股东提现管理-通过id删除")
    @ApiOperation(value = "股东提现管理-通过id删除", notes = "股东提现管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        widthManagementService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "股东提现管理-批量删除")
    @ApiOperation(value = "股东提现管理-批量删除", notes = "股东提现管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.widthManagementService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "股东提现管理-通过id查询")
    @ApiOperation(value = "股东提现管理-通过id查询", notes = "股东提现管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WidthManagement widthManagement = widthManagementService.getById(id);
        if (widthManagement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(widthManagement);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param widthManagement
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WidthManagement widthManagement) {
        //return super.exportXls(request, widthManagement, WidthManagement.class, "股东提现管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<WidthManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, widthManagement, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<WidthManagement> pageList = widthManagementService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "股东提现"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, WidthManagement.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("股东提现数据", "导出人:" + user.getRealname(), "股东提现");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WidthManagement.class);
    }

    /**
     * 修改审核状态 通过传01  驳回传02
     */
    @GetMapping("/updateStatus")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateStatus(@RequestParam("id") String id, @RequestParam("status") String status) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        WidthManagement wm = widthManagementService.getById(id);
        if (!"00".equals(wm.getStatus())) {
            return Result.error("该记录已操作过，不能再次操作");
        }
        wm.setStatus(status);
        wm.setOperator(sysUser.getRealname());
        wm.setOperationTime(new Date());
        widthManagementService.updateById(wm);

        StockManage stock = stockManageService.getById(wm.getStockId());
        if ("01".equals(wm.getStatus())) {
            BigDecimal haveWithdrawal = new BigDecimal(String.valueOf(stock.getHaveWithdrawal()));
            BigDecimal applyAmountB = new BigDecimal(String.valueOf(wm.getApplyAmount()));
            stock.setHaveWithdrawal(haveWithdrawal.add(applyAmountB).doubleValue());
            stockManageService.updateById(stock);

            // 模板消息
            try {
                MemberManagement mm = memberManagementService.getById(stock.getMemberId());
                String gzhOpenId = mm.getGzhOpenId();
                if (gzhOpenId == null) {
                    log.info("发送提现成功模板推送失败，会员未绑定公众号");
                } else {
                    StoreInfo store = storeInfoService.getById(stock.getStoreId());
                    String bossGzhOpenId = storeInfoService.getBossGzhOpenId(stock.getStoreId());
                    if (store == null) {
                        log.info("发送提现成功模板推送失败，未查到店铺信息");
                    } else {
                        String gzhAppId = store.getGzhAppId();
                        String gzhAppSecret = store.getGzhAppSecret();
                        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                            log.info("发送提现成功模板推送失败，店铺未绑定公众号");
                        } else {
                            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                            String result1 = HttpUtils.sendGet(url1);
                            JSONObject resultJson1 = JSON.parseObject(result1);
                            String errcode = resultJson1.getString("errcode");
                            if (errcode != null && !"0".equals(errcode)) {
                                log.info("发送提现成功模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                            } else {
                                String accessToken = resultJson1.getString("access_token");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                MsgTemplate msgTemplate = msgTemplateListService.getByTitle("提现成功通知", store.getId());
                                String templateId = msgTemplate.getTemplateId();
                                util.withdrawalSuccessNotice(templateId, gzhOpenId, String.valueOf(wm.getApplyAmount()), sdf.format(new Date()), store.getXcxAppId(), "user/share/drawal", accessToken);

                                log.info("发送提现成功模板推送成功");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("发送提现成功模板推送失败，发生异常", e);
            }
        }
        if ("02".equals(wm.getStatus())) {
            BigDecimal canWithdrawal = new BigDecimal(String.valueOf(stock.getCanWithdrawal()));
            BigDecimal applyAmountB = new BigDecimal(String.valueOf(wm.getApplyAmount()));
            stock.setCanWithdrawal(canWithdrawal.add(applyAmountB).doubleValue());
            stockManageService.updateById(stock);

            // 模板消息
            try {
                MemberManagement mm = memberManagementService.getById(stock.getMemberId());
                String gzhOpenId = mm.getGzhOpenId();
                if (gzhOpenId == null) {
                    log.info("发送提现驳回模板推送失败，会员未绑定公众号");
                } else {
                    StoreInfo store = storeInfoService.getById(stock.getStoreId());
                    String bossGzhOpenId = storeInfoService.getBossGzhOpenId(stock.getStoreId());
                    if (store == null) {
                        log.info("发送提现驳回模板推送失败，未查到店铺信息");
                    } else {
                        String gzhAppId = store.getGzhAppId();
                        String gzhAppSecret = store.getGzhAppSecret();
                        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                            log.info("发送提现驳回模板推送失败，店铺未绑定公众号");
                        } else {
                            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                            String result1 = HttpUtils.sendGet(url1);
                            JSONObject resultJson1 = JSON.parseObject(result1);
                            String errcode = resultJson1.getString("errcode");
                            if (errcode != null && !"0".equals(errcode)) {
                                log.info("发送提现驳回模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                            } else {
                                String accessToken = resultJson1.getString("access_token");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                MsgTemplate msgTemplate = msgTemplateListService.getByTitle("提现驳回通知", store.getId());
                                String templateId = msgTemplate.getTemplateId();
                                util.withdrawalRjectNotice(templateId, gzhOpenId, stock.getStockName(), String.valueOf(wm.getApplyAmount()), sdf.format(new Date()), store.getXcxAppId(), "user/share/drawal", accessToken);

                                log.info("发送提现驳回模板推送成功");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("发送提现驳回模板推送失败，发生异常", e);
            }
        }

        return Result.OK("操作成功！");
    }

    /**
     * 查询可提现金额
     *
     * @param storeId
     * @param stockId
     * @return
     */
    @AutoLog(value = "查询可提现金额")
    @ApiOperation(value = "查询可提现金额", notes = "查询可提现金额")
    @GetMapping(value = "/getCanWithdrawalAmount")
    public Result<String> getCanWithdrawalAmount(@RequestParam(name = "storeId", required = true) String storeId,
                                                 @RequestParam(name = "stockId", required = true) String stockId) {
        Result<String> result = new Result<String>();
        String canWithdrawalAmount = widthManagementService.getCanWithdrawalAmount(storeId, stockId);
        return Result.OK(canWithdrawalAmount);
    }
//
//    /**
//     * 申请提现
//     * @return
//     */
//    @AutoLog(value = "申请提现")
//    @ApiOperation(value = "申请提现", notes = "申请提现")
//    @RequestMapping(value = "/applyWithdrawal", method = RequestMethod.PUT)
//    public Result<?> applyWithdrawal(@RequestBody JSONObject json) {
//        WidthManagement widthManagement = new WidthManagement();
//        String storeId = json.getString("storeId");
//        String memberId = json.getString("memberId");
//        String applyAmount = json.getString("applyAmount");
//        StockManage stockManage = stockManageService.getByMemberId(memberId);
//        Date date = new Date();
//        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
//        widthManagement.setCreateBy(memberId);
//        widthManagement.setCreateTime(date);
//        widthManagement.setStockId(stockManage.getId());
//        widthManagement.setStockName(stockManage.getStockName());
//        widthManagement.setTel(stockManage.getTel());
//        widthManagement.setEquityBalance(stockManage.getEquityBalance());
//        widthManagement.setLowestLimit(stockManage.getStockLowest());
//        widthManagement.setProfit(String.valueOf(stockManage.getProrateDividends()));
//        widthManagement.setTotalAmount(stockManage.getTotalDividend());
//        widthManagement.setCanWidth(stockManage.getCanWithdrawal());
//        widthManagement.setHaveWidth(stockManage.getHaveWithdrawal());
//        widthManagement.setApplyAmount(Double.valueOf(applyAmount));
//        widthManagement.setInTime(stockManage.getInTime());
//        widthManagement.setHousekeeper(stockManage.getShareholdersHousekeeperId());
//        widthManagement.setDiscount(String.valueOf(stockManage.getShareholderDiscount()));
//        widthManagement.setStatus("01");
//        widthManagement.setRemark("");
//        widthManagement.setStoreId(storeId);
//        widthManagementService.save(widthManagement);
//        return Result.OK("申请成功!");
//    }
}
